#include "filllist.h"
#include "ui_filllist.h"

fillList::fillList(QWidget *parent) :
    QFrame(parent),
    ui(new Ui::fillList)
{
    ui->setupUi(this);
    fillStuff();
    showAll=false;
    dbModel = new myDataModel(this,ui->table,getQuery());

    dbModel->setHeader(QStringList()<<"№"<<"Принят"<<"Клиент"<<"Картриджи"<<"Количество"<<"Выдан"<<"Результат"<<"Примечание"<<"Сотрудник");

    ui->table->show();
    ui->table->scrollTo(dbModel->index(dbModel->rowCount()-1,0));

    connect(ui->table->selectionModel(), SIGNAL(currentRowChanged ( const QModelIndex &, const QModelIndex &)),
            this, SLOT(fcurrentRowChanged( const QModelIndex &, const QModelIndex &)));

    ui->table->horizontalHeader()->setResizeMode(FDB_enumber,QHeaderView::ResizeToContents);
    ui->table->horizontalHeader()->setResizeMode(FDB_indate,QHeaderView::ResizeToContents);
    ui->table->horizontalHeader()->setResizeMode(FDB_outdate,QHeaderView::ResizeToContents);
    ui->table->horizontalHeader()->setResizeMode(FDB_who,QHeaderView::ResizeToContents);
    ui->table->horizontalHeader()->setResizeMode(FDB_quantity,QHeaderView::ResizeToContents);
    ui->table->horizontalHeader()->setResizeMode(FDB_client,QHeaderView::Stretch);
    ui->table->horizontalHeader()->setResizeMode(FDB_comment,QHeaderView::Stretch);
    ui->table->horizontalHeader()->setResizeMode(FDB_result,QHeaderView::Stretch);
    ui->table->horizontalHeader()->setResizeMode(FDB_cartridge,QHeaderView::Stretch);


}

fillList::~fillList()
{
    delete ui;
}

void fillList::updateList()
{
    dbModel->setQuery(getQuery());
}

QString fillList::getQuery()
{
    return showAll?\
                "SELECT * FROM filllist":\
                "SELECT * FROM filllist WHERE outdate is null";
}

void fillList::fillStuff()
{
    QSqlQuery query("SELECT * FROM stafflist ORDER by who DESC");
    while(query.next())ui->whoSelect->insertItem(0,query.value(0).toString());
}

void fillList::fcurrentRowChanged(const QModelIndex &current, const QModelIndex &previous)
{
    ui->clientEdit->setText(dbModel->getData(FDB_client));
    ui->cartridgeEdit->setText(dbModel->getData(FDB_cartridge));
    ui->commentEdit->setText(dbModel->getData(FDB_comment));
    ui->quantityBox->setValue(dbModel->getData(FDB_quantity).toInt());
    ui->whoSelect->setEditText(dbModel->getData(FDB_who));
    ui->resultEdit->setText(dbModel->getData(FDB_result));

}

void fillList::on_addButton_clicked()
{
    if(ui->cartridgeEdit->text().isEmpty()){
        QMessageBox::warning(0,"Ошибка","Введите картриджи.");
        return;
    }
    QSqlQuery query;
    query.prepare("INSERT INTO filllist "
                  "VALUES (DEFAULT,:indate,:client,:cartridge,:quantity,NULL,:result,:comment,:who)");
    query.bindValue(":indate",QDate::currentDate());
    query.bindValue(":result",ui->resultEdit->text());
    query.bindValue(":client",ui->clientEdit->text());
    query.bindValue(":who",ui->whoSelect->currentText());
    query.bindValue(":cartridge",ui->cartridgeEdit->text());
    query.bindValue(":comment",ui->commentEdit->text());
    query.bindValue(":quantity",ui->quantityBox->value());

    query.exec();

    if(query.lastError().isValid())QMessageBox::warning(0,"Неверный запрос",query.lastError().text());

    dbModel->itemAdded();

}

void fillList::on_changeButton_clicked()
{
    if(ui->cartridgeEdit->text().isEmpty()){
        QMessageBox::warning(0,"Ошибка","Введите картриджи.");
        return;
    }

    QSqlQuery query;
    query.prepare("UPDATE filllist "
                  "SET client=:client, cartridge=:cartridge, quantity=:quantity, result=:result,comment=:comment, who=:who "
                  "WHERE enumber=:number");

    query.bindValue(":result",ui->resultEdit->text());
    query.bindValue(":client",ui->clientEdit->text());
    query.bindValue(":who",ui->whoSelect->currentText());
    query.bindValue(":quantity",ui->quantityBox->value());
    query.bindValue(":cartridge",ui->cartridgeEdit->text());
    query.bindValue(":comment",ui->commentEdit->text());
    query.bindValue(":number",dbModel->getData(FDB_enumber));
    query.exec();

    if(query.lastError().isValid())QMessageBox::warning(0,"Неверный запрос",query.lastError().text());

    dbModel->itemChanged();

}

void fillList::on_doneButton_clicked()
{
    if(ui->table->currentIndex().row()<0)return;
    QSqlQuery query;
    query.prepare("UPDATE filllist SET outdate=:outdate WHERE enumber=:number");
    query.bindValue(":outdate",dbModel->getData(FDB_outdate).isEmpty()?QDate::currentDate():QDate::QDate());
    query.bindValue(":number",dbModel->getData(FDB_enumber));
    query.exec();

    if(query.lastError().isValid())QMessageBox::warning(0,"Неверный запрос",query.lastError().text());

    dbModel->setQuery(getQuery());

}

void fillList::on_showallButton_clicked()
{
    showAll=!showAll;
    dbModel->setQuery(getQuery());
    ui->showallButton->setText(showAll?"Текущее":"Все");
}

void fillList::on_searchEdit_returnPressed()
{
    dbModel->setFilterFixedString(ui->searchEdit->text());
}

void fillList::on_delsearchButton_clicked()
{
    ui->searchEdit->clear();
    dbModel->setFilterFixedString("");
}

void fillList::on_searchButton_clicked()
{
    dbModel->setFilterFixedString(ui->searchEdit->text());
}

void fillList::on_exportButton_clicked()
{
    QString excelFilePath=QApplication::applicationDirPath()+"\\fill.xls";
    QTemporaryFile *tempfile=new QTemporaryFile(QDir::tempPath() + QDir::separator() +"XXXXXX.xls");
    tempfile->open();
    QString resname= tempfile->fileName();
    delete tempfile;
    if(!QFile::copy(excelFilePath,resname)){
       QMessageBox::warning(0,"Немогу создать файл",resname);
       return;
    }
    QString strDBName = QString("DRIVER={Microsoft Excel Driver (*.xls)};FIL={MS Excel};READONLY=FALSE;DBQ="+resname);
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC","xls_db");
    db.setDatabaseName(strDBName);
    if (!(db.open())){
        QMessageBox::warning(0,"Ошибка создания отчета",db.lastError().text());
        return;
    }


    for(int r=0;r<dbModel->rowCount();r++){
    QSqlQuery query(db);
    query.prepare("INSERT INTO report "
                  "VALUES (:enumber,:indate,:client,:cartridge,:quantity,:outdate,:result,:comment,:who)");
    query.bindValue(":enumber",dbModel->data(dbModel->index(r,FDB_enumber)).toInt());
    query.bindValue(":indate",dbModel->data(dbModel->index(r,FDB_indate)).toString());
    query.bindValue(":client",dbModel->data(dbModel->index(r,FDB_client)).toString());
    query.bindValue(":cartridge",dbModel->data(dbModel->index(r,FDB_cartridge)).toString());
    query.bindValue(":quantity",dbModel->data(dbModel->index(r,FDB_quantity)).toInt());
    query.bindValue(":outdate",dbModel->data(dbModel->index(r,FDB_outdate)).toString());
    query.bindValue(":result",dbModel->data(dbModel->index(r,FDB_result)).toString());
    query.bindValue(":comment",dbModel->data(dbModel->index(r,FDB_comment)).toString());
    query.bindValue(":who",dbModel->data(dbModel->index(r,FDB_who)).toString());
    query.exec();
    if(query.lastError().isValid()){
        QMessageBox::warning(0,"Неверный запрос",query.lastError().text());
        break;
    }
    query.clear();
}


    db.close();
    QSqlDatabase::removeDatabase("xls_db");

    QDesktopServices::openUrl(QUrl("file:///"+resname));

}
